<template>
  <div>
    <div class="misk"></div>
    <div id="app">
      <div class="imui-center">
        <lemon-imui
          :user="user"
          ref="IMUI"
          :theme="theme"
          :avatar-cricle="true"
          :contact-contextmenu="contactContextmenu"
          :hide-menu="hideMenu"
          :hide-menu-avatar="hideMenuAvatar"
          :hide-message-name="hideMessageName"
          @change-menu="handleChangeMenu"
          @change-contact="handleChangeContact"
          @pull-messages="handlePullMessages"
          @message-click="handleMessageClick"
          @menu-avatar-click="handleMenuAvatarClick"
          @send="handleSend"
        >
          <template #sidebar-message-fixedtop>
            <div class="bar" @click="changeTheme" style="cursor: pointer;background: white;">
              主题切换
            </div>
          </template>
          <template #sidebar-contact-fixedtop>
            <div class="bar">
              <!-- <el-input size="mini"/> -->
              <el-input
                v-model="userName"
                size="mini"
                type="text"
                clearable
                placeholder="搜索"
                prefix-icon="el-icon-search"
                @input="onKeyup"
                @click="visible = !visible"
              />
            </div>
          </template>
        </lemon-imui>
      </div>
       <div class="close" @click="maskClick">
      <i class="el-icon-close"></i>
    </div>
    </div>
    <!-- <div class="attch">
      <i class="lemon-icon-attah" />
    </div>
    <div class="diskTel">
      <disk />
    </div> -->
  </div>
</template>

<script>
import Vue from "vue";
// import { actions } from "@/store/index.js"
import disk from "./disk";
import listNotic from './list'
import emojiData from './emojiData.js'
// import Disk from './disk.vue';
// import LemonMessageVoice from "./lemon-message-voice";
// Vue.component(LemonMessageVoice.name, LemonMessageVoice);

const getTime = () => {
  return new Date().getTime();
};
const generateRandId = () => {
  return Math.random().toString(36).substr(-8);
};
const generateRandWord = () => {
  return Math.random().toString(36).substr(2);
};
const generateMessage = (toContactId, fromUser,content) => {
  if (!fromUser) {
    fromUser = {
      id: "system",
      displayName: "系统测试",
      avatar: "http://upload.qqbodys.com/allimg/1710/1035512943-0.jpg",
    };
  }
  return {
    id: generateRandId(),
    status: "succeed",
    type: "text",
    sendTime: getTime(),
    content: content,
    //fileSize: 1231,
    //fileName: "asdasd.doc",
    toContactId,
    fromUser
  };
};

export default {
  components: { disk,listNotic },
  // vuex: {
  //   actions: actions,
  // },
  props: {
    maskShowClick: {
      type: Function,
    },
    userList:{
      type:Array,
      default:[]
    }
  },
  name: "app",
  data() {
    return {
      hideName: true,
      visible: false,
      userName: "",
      theme: "default",
      ws: this.$store.state.wsobj,
      startpage: 1,
      pagesize: 10,
      // userList: [],
      theme: "default",
      hideMenuAvatar: false,
      hideMenu: false,
      hideMessageName: false,
      user: {
        accNo: window.sessionStorage.getItem("accNo"),
        id: "1",
        name: window.sessionStorage.getItem("userName"),
        avatar:window.sessionStorage.getItem("avatar"),
      },
      contactContextmenu: [
        {
          text: "删除该聊天",
          click: (e, instance, hide) => {
            const { IMUI, contact } = instance;
            IMUI.updateContact({
              id: contact.id,
              lastContent: null,
            });
            if (IMUI.currentContactId == contact.id) IMUI.changeContact(null);
            hide();
          },
        },
        // {
        //   text: "设置备注和标签",
        // }
      ]
    };
  },
  computed:{
     pushMsgObj(){
         return this.$store.state.app.pushMsgObj;
     }
  },
  activated(){
    // this.getUserList();
    var _this = this;
    // this.getMessagesForUser();
    const { IMUI } = this.$refs;
    this.ws.onmessage = (data) => {
     
      let getmessageData = JSON.parse(data.data);
      if(getmessageData.msgType !='01')
      {
        this.sendMsgForOnline(getmessageData);
       console.log(getmessageData, "data1232323");
      }
      
    };
    //未显示数据接收及显示；
    // if(this.pushMsgObj.id)
    // {
    //    _this.getUserList();
    //   setTimeout(function(){
    //      alert(1)
    //    _this.sendMsgForOnline(_this.pushMsgObj)

    //   },500)
    // }
  },
  mounted() {
    // this.getUserList();
    var _this = this;
    // this.getMessagesForUser();
    const { IMUI } = this.$refs;
    this.ws.onmessage = (data) => {
     
      let getmessageData = JSON.parse(data.data);
      if(getmessageData.msgType !='01')
      {
        this.sendMsgForOnline(getmessageData);
       console.log(getmessageData, "data1232323");
      }
    };
    //未显示数据接收及显示；
    if(this.pushMsgObj.id)
    {

      setTimeout(function(){
        _this.sendMsgForOnline(_this.pushMsgObj)
        _this.store.commit("sotreLastedMsg",{});
      },100)
    }
    IMUI.initContacts(this.userList);
    IMUI.initMenus([
      {
        name: "messages",
        // unread: "+0",
      },
      {
        name: "contacts",
      },
       {
        name: "message",
        title: "消息",
        // unread: "+1",
        render: (menu) => {
          return <i class="iconfont icon-gerenxiaoxi_lef_p" style="font-size:20px;" />;
        },
        renderContainer: () => {
          return <listNotic />;
        },
      },
      {
        name: "custom1",
        title: "网盘",
        // unread: 0,
        render: (menu) => {
          return <i class="lemon-icon-attah" />;
        },
        renderContainer: () => {
          return <disk close={this.maskClick}/>;
        },
        isBottom: true,
      },
    ]);
    IMUI.initEmoji(emojiData);
    IMUI.initEditorTools([
      {
        name: "emoji",
      },
      {
        name: "uploadFile",
      },
      {
        name: "uploadImage",
      },
      {
        name: "test1",
        click: () => {
          IMUI.$refs.editor.selectFile("application/vnd.ms-excel");
        },
        render: () => {
          return <span>Excel</span>;
        },
      },
      {
        name: "test1",
        click: () => {
          IMUI.initEditorTools([{ name: "uploadFile" }, { name: "emoji" }]);
        },
        render: () => {
          return <span>重制工具栏</span>;
        },
      },
      {
        name: "test2",
        isRight: true,
        title: "上传 Excel",
        click: () => {
          // alert("点击了 ··· ");
        },
        render: () => {
          return <b>···</b>;
        },
      },
    ]);
    

  },
  created() {
    //this.getUserList();
  },
  methods: {
    sendMsgForOnline(getmessageData){
       var _this = this;
       var userInfo = _this.userList.filter(item => item.id == getmessageData.accFrom);
       const { IMUI } = this.$refs;
      if (getmessageData.content && IMUI) {
          const message = {
            id: getmessageData.accFrom,
            status: "succeed",
            type: "text",
            sendTime: getTime(),
            content: getmessageData.content,
            toContactId: getmessageData.accFrom,
            fromUser: {
              displayName: getmessageData.accFrom,
              avatar: userInfo.length>0?userInfo[0].avatar:"",
              id: getmessageData.accFrom,
            },
          };
        console.log(message, "messagemessagemessage");
        IMUI.appendMessage(message, true);
      }
    },
    //关闭遮罩层
    maskClick() {
      this.maskShowClick();
    },
    // 查询用户目录然后发送消息
    onKeyup(username) {
      // if (e.keyCode == 13) {
        // alert(111)
        this.userName = username;

        var pattern = new RegExp("[\u4E00-\u9FA5]+");
        var pattern2 = new RegExp("[A-Za-z]+");
        let newListData = [];
        //中文判断
        if(pattern.test(username)){
          this.userList.filter((item) => {
            if (item.name.indexOf(this.userName) !== -1) {
              newListData.push(item);
            }
          });
        }//字母判断
        else if(pattern2.test(username)){
          this.userList.filter((item) => {
            if (item.id.indexOf(this.userName) !== -1) {
              newListData.push(item);
            }
          });
        }
        // var userData = this.userList;
        // console.log(userData, "0000000");
        // this.userList.filter((item) => {
        //   if (item.name.indexOf(this.userName) !== -1) {
        //     newListData.push(item);
        //   }
        // });
        const { IMUI } = this.$refs;
        if(username !="")
        {
          IMUI.initContacts(newListData);
        }else{
          IMUI.initContacts(this.userList);
        }
        

        // console.log(newListData, "-++--++--687687*++-684654");
        // this.getUserList();
        // this.search(e.target.value);
      // }
    },
    changeTheme() {
      this.theme = this.theme == "default" ? "blue" : "default";
    },
    changeTheme() {
      this.theme = this.theme == "default" ? "blue" : "default";
    },
    scrollToTop() {
      document.body.scrollIntoView();
    },
    handleMenuAvatarClick() {
      console.log("Event:menu-avatar-click");
    },
    handleMessageClick(e, key, message) {
      console.log("点击了消息", e, key, message);
      const { IMUI } = this.$refs;

      if (key == "status") {
        IMUI.updateMessage(message.id, message.toContactId, {
          status: "going",
          content: "正在重新发送消息...",
        });
        setTimeout(() => {
          IMUI.updateMessage(message.id, message.toContactId, {
            status: "succeed",
            content: "发送成功",
          });
        }, 2000);
      }
    },
    changeMenuAvatarVisible() {
      this.hideMenuAvatar = !this.hideMenuAvatar;
    },
    changeMenuVisible() {
      this.hideMenu = !this.hideMenu;
    },
    changeMessageNameVisible() {
      this.hideMessageName = !this.hideMessageName;
    },
    // 新增消息
    appendMessage() {

      const { IMUI } = this.$refs;
      const contact = IMUI.currentContact;
      const message = generateMessage();
      message.fromUser = {
        ...message.fromUser,
        ...this.user,
      };

      // console.log(message.fromUser, "message.fromUser");
      IMUI.appendMessage(message,true);
      // IMUI.updateContact(contact.id, {
      //   // unread: "+10",
      //   lastSendTime: getTime(),
      //   lastContent: IMUI.lastContentRender(message),
      // });
    },
    // updateContact() {
    //   this.$refs.IMUI.updateContact("contact-3", {
    //     unread: 10,
    //     displayName: generateRandWord(),
    //     lastSendTime: getTime(),
    //     lastContent: "修改昵称为随机字母",
    //   });
    // },
    //发送消息按钮
    handleChangeContact(contact, instance) {

      console.log("Event:change-contact");
      instance.updateContact({
        id: contact.id,
        unread: 0,
        // lastSendTime: getTime(),
        // lastContent: "修改昵称为随机字母",
      });
      // instance.closeDrawer();
      
    },
    //获取消息
    getMessagesForUser(){
       var params = {
        id: "001",
        from: "zhangqing",
        action: "pull",
        startpage:"1",
        pagesize:"10"
      };
      this.ws.send(JSON.stringify(params));
    },
    handleSend(message, next, file) {
      console.log(message, next, file, "file");
      var params = {
        id: "001",
        to: message.toContactId,
        action: "push",
        content: message.content,
      };
      // this.changeList = JSON.parse(localStorage.getItem("userListData"));
      this.ws.send(JSON.stringify(params));
      for (var item in this.userList) {
        if (this.userList[item].id == message.toContactId) {
          this.userList[item].lastContent = message.content;
          this.userList[item].lastSendTime = message.sendTime;
          // this.userList[item].unread = 0;
          break;
        }
      }
      // console.log(this.changeList, "this.changeList");
      // localStorage.setItem("userListData", JSON.stringify(this.changeList));

      this.$refs.IMUI.getMessages(message.toContactId)
      setTimeout(() => {
        next();
      }, 1000);
    },
    //点击用户时触发
    handlePullMessages(contact, next) {
      console.log(contact, "------+++++++");
      const { IMUI } = this.$refs;
      console.log(this.user)
      const otheruser = {
        id: contact.id,
        displayName: contact.name,
        avatar: contact.avatar,
      };

      console.log("本地数据",IMUI.getMessages(contact.id));
      // var msg = IMUI.getMessages(contact.id);
      // console.log(otheruser, "otheruser");
      // console.log("Event:pull-messages");
      // alert(IMUI.currentContactId);
      // alert(JSON.stringify(otheruser));
      // localStorage.setItem("contact", JSON.stringify(contact));
      const messages = [];
      // let isEnd = false;
      // if (IMUI.getMessages(IMUI.currentContactId).length > 20) isEnd = true;
      var msg = generateMessage(this.user.accNo, otheruser,contact.lastContent);
      if(contact.lastContent == " " || contact.lastContent == ""){
         delete msg.content;
      }
      // alert(JSON.stringify(msg))
      messages.push(msg)
      next(messages, true);
           
    },
    handleChangeMenu() {
      console.log("Event:change-menu");
      this.onKeyup("");
    },
    openCustomContainer() {},
  },
};
</script>

<style lang="less" scoped>
.close {
  position: absolute;
  cursor: pointer;
  right: 15px;
  top: 14px;
  z-index: 777;
}
.misk {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  opacity: 0.6;
  background: black;
  z-index: 2027;
}

.search {
  border: none;
  padding: 2px 10px;
  // width: 100%;
  font-size: 12px;
  // color: #fff;
  height: 22px;
  line-height: 24px;
  // border: solid 1px #3a3a3a;
  border-radius: 4px;
  outline: none;
  // background-color: #26292e;
}
// ::selection {
//   background: #000;
//   color: #fff;
// }

// body {
//   background: #f6f6f6 !important;
// }

#app {
  position: absolute;
  // width: 100%;
  margin: 0 auto;
  padding-bottom: 100px;
  top: 15%;
  left: 25%;
  z-index: 9999;
  .scroll-top {
    cursor: pointer;
    position: fixed;
    bottom: 40px;
    left: 50%;
    border-radius: 50%;
    background: #fff;
    font-size: 18px;
    overflow: hidden;
    width: 40px;
    height: 40px;
    line-height: 40px;
    user-select: none;
    text-align: center;
    transform: rotate(-45deg) translateX(-50%);
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.1);

    &:hover {
      font-size: 22px;
    }
  }
}

a {
  color: #0c5ed9;
  text-decoration: none;
  font-size: 12px;
}

.action {
  margin-top: 20px;

  .lemon-button {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.link {
  font-size: 14px;
  margin-top: 15px;

  a {
    display: inline-block;
    margin: 0 5px;
    text-decoration: none;
    background: #ffba00;
    border-radius: 4px;
    padding: 5px 10px;
    color: rgba(0, 0, 0, 0.8);
  }
}

.imui-center {
  margin-bottom: 60px;

  .lemon-wrapper,
  .lemon-wrapper--drawer-show .lemon-drawer {
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.1);
  }
}

.drawer-content {
  padding: 15px;
}

.more {
  font-size: 32px;
  line-height: 18px;
  height: 32px;
  position: absolute;
  top: 6px;
  right: 14px;
  cursor: pointer;
  user-select: none;
  color: #999;

  &:active {
    color: #000;
  }
}

.cover {
  text-align: center;
  user-select: none;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  i {
    font-size: 84px;
    color: #e6e6e6;
  }

  p {
    font-size: 18px;
    color: #ddd;
    line-height: 50px;
  }
}

.bar {
  text-align: center;
  line-height: 30px;
  // background: #fff;
  margin: 15px;
  color: #666;
  user-select: none;
  font-size: 12px;
}
</style>
